package com.cgly.medical.security;

import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson.JSON;
import com.cgly.medical.domain.Account;
import com.cgly.medical.entity.AccountModel;
import com.cgly.medical.model.AccountInfoModel;
import com.cgly.medical.service.impl.UserDetailsServiceImpl;
import com.cgly.medical.util.JwtUtils;
import com.cgly.medical.util.Msg;
import com.cgly.medical.util.MyJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.UUID;

/**
 * 获取用户登录的信息并生成对应的jwtToken和用户基本信息数据并返回给前端数据,
 * @program: medical
 * @description: 登录成功处理器
 * @author: chen di
 * @create: 2022-08-15 16:34
 */
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    UserDetailsServiceImpl myUserService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        System.out.println("登录成功");
        String name = authentication.getName();
        AccountModel user = myUserService.loadUserByUsername(name);
        user.setPwd("");
        user.setSalt("");


        //token    1000*60*60*24
        String token = MyJWT.createJWT(UUID.randomUUID().toString(),JSON.toJSONString(user),3600 * 24 * 1000 );
        System.out.println("加密后：" +token);
        Claims claims = MyJWT.parseJWT(token);
        System.out.println("解密后：" + claims.getSubject());

        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(JSON.toJSONString(Msg.success().mess("登录成功").data("token",token)
                .data("name",name).data("roles",user.getUtype())
                .data("avatar","https://img1.baidu.com/it/u=2003496092,3295249130&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1661706000&t=bbfa7fce8bd6eb141a9d2fddd1a0182e")
        .data("user",user)));
//        response.getWriter().write(JSON.toJSONString(Msg.success().data("roles","[admin]").data("name","admin").data("avatar","https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif")));

    }
}